package com.codez.wechat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 
 * @author 干净的代码
 * @创建时间 ： 2019-10-16
 * 
 */
@RequestMapping("wx")
@Controller
public class WxController {

	@Autowired
	WxMpService wxMpService;

	//mpService.oauth2buildAuthorizationUrl("http://codez.free.idcfengye.com/wx",  WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
	
	@RequestMapping("auth")
	public String auth(String openid) {
		return "redirect:" + wxMpService.oauth2buildAuthorizationUrl("http://codez.free.idcfengye.com/wx/userInfo",  WxConsts.OAuth2Scope.SNSAPI_USERINFO, "codez_state");
	}

	@RequestMapping("userInfo")
	public String userInfo(String code , String state , Model model) throws WxErrorException {
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		model.addAttribute("user", wxMpUser);
		model.addAttribute("state", state);
		System.out.println(state);
		return "index";
	}
	
}
